#!/usr/bin/python3
from socket import if_nameindex
from threading import main_thread
import pymongo
import json
from pymongo import collection

from pymongo.mongo_client import MongoClient

class JsonToMongo(object):
    def __init__(self):
        self.host = 'localhost'
        self.port = 27017


    def __open_file(self):
        self.file = open('data.json','r',encoding='utf-8')
        self.client = MongoClient(self.host,self.port)
        self.mydb = self.client['data']
        dblist = self.client.list_database_names()
        if 'data' in dblist:
            print("数据库已经存在或者申请成功！")
        self.collect = self.mydb['jobs']
        # collist = self.collect.name()
        # if 'jobs' in collist:
            # print("集合已存在或者申请集合成功！")

    def __close_file(self):
        self.file.close

    def write_database(self):
        self.__open_file()
        data = json.load(self.file)
        try:
            self.collect.insert(data)
            print('写入成功')
        except Exception as e:
            print(e)
        finally:
            self.__close_file


if __name__ == '__main__':
    j2m = JsonToMongo()
    j2m.write_database()


